package br.com.fiap.mercadinho.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.fiap.mercadinho.bean.User;
import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.common.RequestKey;
import br.com.fiap.mercadinho.common.UserType;
import br.com.fiap.mercadinho.dao.UserDAO;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserDAO dao = new UserDAO();
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		String typeUser = request.getParameter("type");
		
		if (login == null || login.equals("")){
			request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
					"Campo login é obrigatório.");
			sendResponse(request, response,"user.jsp");
		}else if (password == null || password.equals("")){
			request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
					"Campo login é obrigatório.");
			sendResponse(request, response,"user.jsp");
		}
		
		try {
			if (dao.findUserByLogin(login)== null){
				
				User user = new User();
				user.setLogin(login);
				user.setPassword(password);
				user.setUserType(UserType.fromString(typeUser));
				dao.addUser(user);
				request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
						"Usuario adicionado com sucesso");
				
			}else{
				request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
						"O login: " + login + " já esta sendo utilizado.");
			}
			
			sendResponse(request, response, "user.jsp");
			
		} catch (DAOException e) {
			request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
					"Erro ao efetuar cadastro do usuario: " + e.getMessage());
		}
		
	}
	
	private void sendResponse(HttpServletRequest request,
			HttpServletResponse response,String page) throws ServletException, IOException {
		request.getRequestDispatcher(page).forward(request, response);
	}


}
